import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Product Detail',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'PingFang SC', // Use a Chinese-compatible font
      ),
      home: const ProductDetailPage(
        arguments: {},
      ),
    );
  }
}

class ProductDetailPage extends StatelessWidget {
  final Map arguments;
  const ProductDetailPage({Key? key, required this.arguments})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 246, 246, 246),
      appBar: AppBar(
        // title: const Text('商品详情'),
        // centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.home),
            onPressed: () {},
          ),
          IconButton(
            icon: const Icon(Icons.collections),
            onPressed: () {},
          ),
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: () {},
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildImageGallery(arguments),
            _buildPriceSection(context, arguments),
            _buildProductTitle(arguments),
            _buildSelectionSection(),
            _buildPromotionInfo(),
            _buildSimilarProducts(),
            _buildEvaluate(),
          ],
        ),
      ),
      persistentFooterButtons: [
        _buildBottomBar(context),
      ],
    );
  }

  Widget _buildImageGallery(Map arguments) {
    return SizedBox(
      height: 300,
      child: Stack(
        children: [
          PageView.builder(
              itemCount: 1,
              itemBuilder: (context, index) {
                String imagePath =
                    arguments['img'] ?? "../../../assets/images/default.jpg";
                return Image.asset(imagePath, fit: BoxFit.cover);
              }),
          Positioned(
            top: 20,
            right: 20,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(10),
              ),
              child: const Text(
                '1/1',
                style: TextStyle(color: Colors.white, fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPriceSection(context, arguments) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Text(
                '到手价',
                style: TextStyle(
                    fontSize: 14, color: Color.fromARGB(255, 241, 72, 85)),
              ),
              const SizedBox(width: 8),
              Text(
                '￥${arguments['price']}',
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                  color: Color.fromARGB(255, 241, 72, 85),
                ),
              ),
              const SizedBox(width: 8),
              Text(
                '优惠前￥${arguments['originalPrice']}',
                style: TextStyle(
                  fontSize: 14,
                  color: Color.fromARGB(255, 241, 72, 85),
                  decoration: TextDecoration.lineThrough,
                ),
              ),
              Spacer(),
              Text("销量1200+",
                  style: TextStyle(color: Color.fromARGB(255, 161, 159, 168)))
            ],
          ),
          const SizedBox(height: 8),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                _buildCouponTag(
                    '10元无门槛券', Color.fromARGB(80, 241, 72, 85), Colors.red),
                _buildCouponTag(
                    '满200减60券', Color.fromARGB(80, 241, 72, 85), Colors.red),
                _buildCouponTag('限购金起2元', Color.fromARGB(128, 245, 224, 31),
                    const Color.fromARGB(255, 244, 220, 4)),
                TextButton(
                  onPressed: () {},
                  child: const Text(
                    '领取 >',
                    style: TextStyle(
                      color: Colors.red,
                      fontWeight: FontWeight.bold, // 设置字体加粗
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCouponTag(String text, Color borderColor, Color textColor) {
    return Container(
      margin: const EdgeInsets.only(right: 8),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: borderColor, // 背景颜色
        border: Border.all(color: Colors.transparent), // 边框颜色设为透明
        borderRadius: BorderRadius.circular(4), // 圆
      ),
      child: Text(
        text,
        style: TextStyle(color: textColor, fontSize: 12),
      ),
    );
  }

  Widget _buildProductTitle(arguments) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      width: double.infinity, // 让Container宽度填满父元素的宽度
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '${arguments['name']}',
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 4),
          Text(
            '${arguments['desc']}',
            style: TextStyle(fontSize: 14, color: Colors.grey[600]),
          ),
        ],
      ),
    );
  }

  Widget _buildSelectionSection() {
    return Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        margin: const EdgeInsets.symmetric(vertical: 10),
        child: Row(
          children: [
            Text(
              '选择：请选择商品规格',
              style: TextStyle(fontSize: 14),
            ),
            Spacer(),
            const Icon(Icons.chevron_right),
          ],
        ));
  }

  Widget _buildPromotionInfo() {
    return Container(
      color: Colors.white,
      margin: const EdgeInsets.symmetric(vertical: 10),
      width: double.infinity, // 让Container宽度填满父元素的宽度
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          const Text('活动'),
          const SizedBox(width: 8),
          const Text('[满折] 满400打八折',
              style: TextStyle(
                color: Color.fromARGB(255, 239, 127, 134),
              )),
          Spacer(),
          const Icon(Icons.chevron_right),
        ],
      ),
    );
  }

  Widget _buildSimilarProducts() {
    final similarData = [
      {'img': '../../../assets/images/chrimis.jpg', 'price': 15},
      {'img': '../../../assets/images/cup.jpg', 'price': 23.6},
      {'img': '../../../assets/images/weijin.jpg', 'price': 60.2},
      {'img': '../../../assets/images/mouse.jpg', 'price': 151.1},
    ];
    return GridView.builder(
        // padding: const EdgeInsets.all(16),
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 0.5,
          mainAxisSpacing: 8,
          crossAxisSpacing: 8,
        ),
        itemCount: similarData.length,
        itemBuilder: (context, index) => Container(
              color: Colors.white,
              padding: const EdgeInsets.all(8),
              child: Column(children: [
                Image.asset(
                  similarData[index]['img'] as String,
                  cacheWidth:
                      (MediaQuery.of(context).size.width * 0.93).toInt(),
                  cacheHeight:
                      (MediaQuery.of(context).size.height * 0.75).toInt(),
                  fit: BoxFit.cover,
                ),
                const SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "￥" + similarData[index]['price'].toString(),
                      style: TextStyle(
                          color: Color.fromARGB(255, 230, 135, 146),
                          fontSize: 20),
                    ),
                    Image.asset(
                      '../../../assets/icons/redShopCar.png',
                      width: 25,
                      height: 25,
                    )
                  ],
                )
              ]),
            ));
  }

  Widget _buildEvaluate() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              Text(
                "商品评价(128)",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
              ),
              Spacer(),
              Text(
                "更多",
                style: TextStyle(color: Color.fromARGB(255, 142, 140, 153)),
              )
            ],
          ),
          Row()
        ],
      ),
    );
  }

  Widget _buildBottomBar(context) {
    return Container(
      height: 60,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Colors.grey[200]!)),
      ),
      child: Row(
        children: [
          // 左侧图标按钮
          _buildIconButton(Icons.headset_mic, '客服', context),
          _buildIconButton(Icons.shopping_cart, '购物车', context),
          Spacer(),
          _buildActionButton(Colors.yellow, "加入购物车", context),
          _buildActionButton(Colors.red, "领卷购买", context)
        ],
      ),
    );
  }

  Widget _buildIconButton(IconData icon, String text, context) {
    // 获取传递的参数

    return SizedBox(
      width: 60,
      child: TextButton(
        style: TextButton.styleFrom(
          padding: EdgeInsets.zero,
        ),
        onPressed: () {
          Navigator.pushNamed(context, '/shopCar', arguments: arguments);
        },
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 24, color: Colors.grey[700]),
            Text(text, style: TextStyle(fontSize: 10, color: Colors.grey[700])),
          ],
        ),
      ),
    );
  }

  Widget _buildActionButton(Color color, String text, context) {
    return Container(
      margin: EdgeInsets.all(4),
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: color,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          //   padding: EdgeInsets.symmetric(vertical: 12),
        ),
        onPressed: () async {
          if (text == '加入购物车') {
            try {
              await addProductToCart(
                  Product.fromMap(Map<String, dynamic>.from(arguments)));
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('已添加到购物车')),
              );
            } catch (e) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('添加失败: $e')),
              );
            }
          }
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}

Future<void> addProductToCart(Product product) async {
  try {
    final prefs = await SharedPreferences.getInstance();
    List<String> cart = prefs.getStringList('cart') ?? [];
    
    // 检查商品是否已存在
    bool exists = cart.any((item) {
      final existing = json.decode(item);
      return existing['name'] == product.name &&
          existing['desc'] == product.desc;
    });

    if (!exists) {
      cart.add(json.encode(product.toMap()));
      await prefs.setStringList('cart', cart);
      print('商品已添加到购物车');
      print("${cart}1111111");
    } else {
      print('商品已在购物车中');
    }
  } catch (e) {
    print('保存到购物车失败: $e');
    // 可以考虑在这里添加备用存储方案
  }
}

class Product {
  String name;
  String desc;
  String originalPrice;
  String price;
  String img;

  Product({
    required this.name,
    required this.desc,
    required this.originalPrice,
    required this.price,
    required this.img,
  });

  // 将 Product 转换为 Map
  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'desc': desc,
      'originalPrice': originalPrice,
      'price': price,
      'img': img,
    };
  }

  // 从 Map 创建 Product
  factory Product.fromMap(Map<String, dynamic> map) {
    return Product(
      name: map['name'],
      desc: map['desc'],
      originalPrice: map['originalPrice'],
      price: map['price'],
      img: map['img'],
    );
  }
}
